<template>
    <div id='chapter'>
        <div id="header">
            <span class="am-icon-mortar-board">  </span>
        </div>
        <a href="#header" class="returnTop" v-if="page == 'chapter'">
                <div style="width: 100%;height: 32px;"></div>
                <span style="display:inline-block;margin8-top: 5px">返回顶部</span>
	    </a>
        <div class="err_head">
                <h1>{{title}}</h1>
                <div :class="page == 'chapter' || page == 'error'?'err_info_chapter':'err_info'">
                    <small><span class="am-icon-map-marker"></span> 科目：{{subjectName}}-{{categoryName}}</small>　
                    <small v-if="page == 'chapter' || page == 'error'"><span class="am-icon-file-text-o"></span> 来源：{{source}} </small>　　
                    <a id="saveProcess" href="javascript:void(0);" class="am-btn am-btn-sm" type="button" @click='saveJindu' v-if="page == 'chapter'">
                        <span class="am-icon-save"></span>
                        保存进度，下次继续
                    </a>
                    <!-- <a id="saveError" href="javascript:void(0);" style="color:#f37b1d" class="am-btn am-btn-sm" type="button" @click='saveErr' v-if="page == 'chapter'">
                        <span class="am-icon-save"></span>
                        做题完毕，保存错题
                    </a> -->
                </div>
        </div>
        <Exam :examList='examList' :scrollRight='scrollRight' @judge ='judgeIsDo' :page='page' :examData='examData' @getData='getPlanDatas' v-if='examData'/>
    </div>
</template>

<script>
import Exam from '../../components/common/examination.vue';
import EventBus from '../../utils/eventBus';
import { clearInterval } from 'timers';
import { getExams ,getWrongQuestions,getCollection,getPaperProgress} from '../../api/chapter';
export default {
    components:{
        Exam
    },
    data(){
        return{
            //头部信息
            subjectName:'',
            categoryName:'',
            subject:'',
            source:'',
            title:"章节练习",
            // 类型id
            subjectId:'',
            //试题内容
            examList:[],
            //是否让右侧答题卡固定在上方
            scrollRight:false,
            //是否可以交卷
            judgeBool:false,
            //试卷类型，章节练习，我的收藏和错题强化
            page:'chapter',
            // 试题数据
            examData:null,
            // 保存进度的数据
            planData:null,
            // 章节练习开始时间
            startTime:null
        }
    },
    created(){
        if(localStorage.getItem('categoryName')){
            this.categoryName = localStorage.getItem('categoryName')
        }
        if(localStorage.getItem('subjectName')){
            this.subjectName = localStorage.getItem('subjectName')
        }
        if(localStorage.getItem('categoryId')){
            this.subjectId = localStorage.getItem('categoryId');
        }
        //判断什么试卷有不同的头部信息
        this.page = this.$route.query.page || 'chapter';
        if(this.page == 'chapter'){
            this.title = '章节练习';
            this.source = this.$route.query.paperName;
            this.startTime = new Date().getTime();
            if(this.$route.query.entrance == 'zhangjie'){
                // this.$get("/api/v1/exams/" + this.$route.query.id)
                getExams(this.$route.query.id)
                .then(res=>{
                    if(res.code == 200){
                        let obj = {};
                        for(let i in res.data){
                            if(typeof(res.data[i]) == 'object' && res.data[i]!=null){
                                obj[i] = res.data[i]
                            }
                        }
                        this.examData = obj || {}
                    }else{
                        this.$message.error('获取章节练习详情失败，请重试');
                    }
                })
            }else if(this.$route.query.entrance == 'jindu'){
                // this.$get("/api/v1/paper_progress/" + this.$route.query.progressID)
                getPaperProgress(this.$route.query.progressID)
                .then(res=>{
                    if(res.code == 200){
                        let obj = {};
                        for(let i in res.data){
                            if(typeof(res.data[i]) == 'object' && res.data[i]!=null){
                                obj[i] = res.data[i]
                            }
                        }
                        this.examData = obj || {}
                    }else{
                        this.$message.error('获取章节练习进度详情失败，请重试');
                    }
                })
            }
        }else if(this.page == 'collect'){
            this.title = '我的收藏'
            // this.$get(`/api/v1/collection/${this.subjectId}`)
            getCollection(this.subjectId)
            .then(res=>{
                if(res.code == 200){
                    this.examData = res.data || null;
                }else{
                    this.$message.error('获取收藏列表失败，请重试');
                }
            })
        }else if(this.page == 'error'){
            this.title = '错题强化训练'
            this.getWrongQuestion();
        }
    },
    methods:{
        // 获取错题列表
        async getWrongQuestion(){
            let exams = {}
            let result = {}
            await getExams(this.$route.query.paperId)
            .then(res=>{
                if(res.code == 200){
                    this.source = res.data.name
                    for(let i in res.data){
                        if(typeof(res.data[i]) == 'object' && res.data[i]!=null){
                            // exams = exams.concat(res.data[i])
                            exams[i] = res.data[i]
                        }
                    }
                }else{
                    this.$message.error('获取错题失败，请重试');
                }
            })
            await getWrongQuestions({subjectId:this.subjectId})
            .then(res=>{
                if(res.code == 200){
                    result = res.data
                }else{
                    this.$message.error('获取错题详情失败，请重试');
                }
            })
            this.processingData(exams,result);
        },
        // 处理错题的列表
        processingData(exams,result){
            let examsObj = {
                calculationAnswers: [],
                calculations: [],
                caseStudies: [],
                comprehensives: [],
                indefinite: [],
                judgments: [],
                multiples: [],
                radio: [],
                showAnswers: []
            }
            for(let i in exams){
                for(let j in result){
                    if(exams[i].length == 0 || result[j].length == 0) continue;
                    if(i == j){
                        // console.log(exams[i],'exam')
                        // console.log(result[j],'result')
                        for(let p = 0;p<exams[i].length;p++){
                            for(let q = 0;q<result[j].length;q++){
                                if(exams[i][p].questionId == result[j][q].questionId){
                                    examsObj[i].push(exams[i][p])
                                }
                            }
                        }
                    }
                }
            }
            this.examData = examsObj
            // for(let i = 0;i<exams.length;i++){
            //     for(let j = 0;j<result.length;j++){
            //         if(exams[i].questionId == result[j].questionId){
            //             wrongData.push(exams[i])
            //             continue;
            //         }
            //     }
            // }
            // wrongData.forEach(item=>{
            //     switch (item.type){
            //         case '0':
            //           examsObj.radio.push(item)
            //           break;
            //           case '1':
            //           examsObj.multiples.push(item)
            //           break;
            //           case '2':
            //           examsObj.indefinite.push(item)
            //           break;
            //           case '3':
            //           examsObj.judgments.push(item)
            //           break;
            //           case '4':
            //           examsObj.showAnswers.push(item)
            //           break;
            //           case '5':
            //           examsObj.calculations.push(item)
            //           break;
            //           case '6':
            //           examsObj.comprehensives.push(item)
            //           break;
            //           case '7':
            //           examsObj.calculationAnswers.push(item)
            //           break;
            //           case '8':
            //           examsObj.caseStudies.push(item)
            //           break;
            //           default:break;
            //       }
            // })
            
        },
        //右侧答题卡固定在首部，用scrollRight控制class样式
        rightScroll(e){
            if(document.documentElement.scrollTop > 265 || document.documentElement.scrollTop == 265){
                this.scrollRight = true
            }else{
                this.scrollRight = false
            }
        },
        //子传父控制的方法，用来判断是否可以交卷
        judgeIsDo(boolean){
            this.judgeBool = boolean;
        },
        // 获取保存进度的数据
        getPlanDatas(arr){
           this.planData = arr;
        },
        // 保存进度的方法
        saveJindu(){
            // layer.msg('正在开发，敬请期待');
            // return;
            if(this.judgeBool){
                this.$confirm('确定要保存进度吗，点击"确定"后继续', '信息', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                    this.$prompt('给进度起个名称吧', '保存进度', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                        }).then(({ value }) => {
                            if(value){
                                EventBus.$emit('getPlanData');
                                let progressData = {
                                    name:value,
                                    paperId:this.$route.query.id,
                                    duration:Math.round((new Date().getTime() - this.startTime)/1000),
                                    questionProgresses:this.planData
                                }
                                this.$post("/api/v1/paper_progress", progressData)
                                .then(res=>{
                                    if(res.code == 200){
                                        this.$message({
                                            type: 'success',
                                            message: '保存成功!'
                                        });
                                    }else{
                                        layer.msg(res.msg,{icon: 2});
                                    }
                                })
                            }else{
                                layer.msg('请填写进度名称',{icon: 5});
                            }
                        }).catch(() => {});
                }).catch(() => {});
            }else{
                layer.msg('您尚未做题',{icon: 2});
            }
        },
        // 保存错题的方法
        saveErr(){
            if(this.judgeBool){
                this.$confirm('错题已保存，是否离开页面查看错题强化', '信息', {
                confirmButtonText: '确定',
                cancelButtonText: '取消' ,
                }).then(() => {
                    // this.$message({
                    //     type: 'success',
                    //     message: '保存成功!'
                    // });
                    EventBus.$emit('getPlanData');
                    let obj = {
                        paperId:this.$route.query.id,
                        duration:Math.round((new Date().getTime() - this.startTime)/1000),
                        questionProgresses:this.planData,
                        startTime:this.crtTimeFtt(this.startTime)
                    }
                    console.log(obj)
                }).catch(() => {
                });
            }else{
                layer.msg('您尚未做题!');
            }
        },
        //格式化时间
        crtTimeFtt(val) {
            if (val != null) {
                var date = new Date(val);
                return (
                this.myformatter(date.getFullYear()) +
                "-" +
                this.myformatter(date.getMonth() + 1) +
                "-" +
                this.myformatter(date.getDate()) +
                " " +
                this.myformatter(date.getHours()) +
                ":" +
                this.myformatter(date.getMinutes()) +
                ":" +
                this.myformatter(date.getSeconds())
                );
            }
        },
        //补位
        myformatter(val) {
            if (val < 10) {
                return "0" + val;
            } else {
                return val;
            }
        },
    },
    mounted(){
        //阻止右键点击事件呼出浏览器菜单
        document.oncontextmenu = function(){
        　　return false;
        }
        //监听页面滚动的事件
        window.addEventListener('scroll',this.rightScroll,true)
    },
    destroyed(){
        //页面销毁时取消监听事件
         window.removeEventListener('scroll',this.rightScroll)
    }
}
</script>

<style lang="scss" scoped>
@import url('../../assets/radioCheckbox.css');
    #chapter{
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        width:100%;
        min-width:1200px;
        background:#fff;
        height:auto;
        min-height:100vh;
        #header{
                height: 50px;
                display: flex;
                justify-content: flex-start;
                padding-left: 20px;
                align-items: center;
                background: #0E90D2;
                color: #fff;
        }
        .returnTop{
                position: fixed;
                bottom: 20px;
                right: 30px;
                text-align: center;
                color: #333333;
                font-size: 14px;
                div{
                    background: url('../../static/images/return-top.png') center no-repeat;
                }
            }
        
        
        .err_head{
                width:1200px;
                height: 180px;
                display: flex;
                margin:0 auto;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                background: #fff;
                border: 1px solid #e0e3e9;
                border-radius: 3px;
                margin-top: 35px;
                small{
                    font-size:80%;
                }
                h1{
                    flex: 2;
                    font-size: 3.8rem;
                    display: flex;
                    align-items: flex-end;
                    margin: 0;
                    letter-spacing: 2px;
                    text-align: center;
                }
                .err_info {
                    flex: 1;
                    display: flex;
                    align-items: center;
                    width:60%;
                    flex-direction: row;
                    justify-content: center;
                }
                .err_info_chapter{
                    flex: 1;
                    display: flex;
                    align-items: center;
                    width:60%;
                    flex-direction: row;
                    justify-content: space-around;
                }
            }
    }
</style>